//
//  ExamQuestionReadCollectionViewCell.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/19.
//

#import "ExamQuestionReadCollectionViewCell.h"
#import "ExamQuestionsListCell.h"
#import <WebKit/WebKit.h>


@interface ExamQuestionReadCollectionViewCell()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,WKUIDelegate,WKNavigationDelegate>

@property(nonatomic,strong)UIScrollView *bgScrollView;
@property(nonatomic,strong)UIView *questionView;
@property(nonatomic,strong)WKWebView *questionWebView;
@property(nonatomic,strong)WKWebView *qContentWebView;//大题内容
@property(nonatomic,strong)WKWebView *contentWebView;//阅读内容
@property(nonatomic,strong)WKWebView *mergeWebView;//抽出来的合并的小题题干内容
@property(nonatomic,strong)UIScrollView *btnScrollView;
@property(nonatomic,strong)UIScrollView *tvScrollView;
@property(nonatomic,strong)UIView *line;
@property(nonatomic,strong)UILabel *optionTitleLabel;
@property(nonatomic,assign)CGFloat max_h;
@property(nonatomic,assign)CGFloat total_top;
@property(nonatomic,strong)UIView *topView;

@end

@implementation ExamQuestionReadCollectionViewCell

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.currentAvailableWidth = frame.size.width;
        self.currentAvailableHeight = frame.size.height+kYM_NAVIGATIONBAR_HEIGHT+38;
        [self createUI];
    }
    return self;
}

-(void)createUI{
    
    self.backgroundColor = UIColorHex(0xF2F7F6);
    
    self.topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,40)];
    self.topView.backgroundColor = UIColorHex_(0xFF781D,0.1);
    [self.contentView addSubview:self.topView];
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.backgroundColor = [UIColor clearColor];
    tipLabel.font = JPUIFontPingFangSCRegular(14);
    tipLabel.textColor = UIColorHex_(0xFF781D,0.8);
    tipLabel.text = @"*本题不支持作答，可在交卷后查看翻译";
    [self.topView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(@10);
        make.left.mas_equalTo(@16);
        make.height.mas_equalTo(@20);
        make.right.mas_equalTo(@-16);
    }];
    self.topView.hidden = YES;
    
    self.bgScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0, self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-38)];
    self.bgScrollView.backgroundColor = UIColorHex(0xF2F7F6);
    self.bgScrollView.showsVerticalScrollIndicator = NO;
    [self.contentView addSubview:self.bgScrollView];
    
    //大题题目
    self.questionView = [[UIView alloc]initWithFrame:CGRectMake(16,14,self.currentAvailableWidth-32,0)];
    self.questionView.layer.cornerRadius = 10;
    self.questionView.layer.masksToBounds = YES;
    self.questionView.backgroundColor = UIColorHex_(0xFF781D,0.1);
    [self.bgScrollView addSubview:self.questionView];
    NSString *jScript0 = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 64];
    WKUserScript *wkUScript0 = [[WKUserScript alloc] initWithSource:jScript0 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController0 = [[WKUserContentController alloc] init];
    [wkUController0 addUserScript:wkUScript0];
    WKWebViewConfiguration *wkWebConfig0 = [[WKWebViewConfiguration alloc] init];
    wkWebConfig0.userContentController = wkUController0;
    self.questionWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16, 10, self.currentAvailableWidth - 64,0) configuration:wkWebConfig0];
    self.questionWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.questionWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.questionWebView.UIDelegate = self;
    self.questionWebView.navigationDelegate = self;
    self.questionWebView.scrollView.bounces = NO;
    self.questionWebView.backgroundColor = [UIColor clearColor];
    self.questionWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.questionWebView.scrollView.scrollEnabled = NO;
    self.questionWebView.opaque = NO;
    [self.questionView addSubview:self.questionWebView];
    self.questionView.hidden = YES;
    
    //大题内容
    NSString *jScript2 = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 32];
    WKUserScript *wkUScript2 = [[WKUserScript alloc] initWithSource:jScript2 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController2 = [[WKUserContentController alloc] init];
    [wkUController2 addUserScript:wkUScript2];
    WKWebViewConfiguration *wkWebConfig2 = [[WKWebViewConfiguration alloc] init];
    wkWebConfig2.userContentController = wkUController2;
    self.qContentWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16,24,self.currentAvailableWidth-32,0) configuration:wkWebConfig2];
    self.qContentWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.qContentWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.qContentWebView.UIDelegate = self;
    self.qContentWebView.navigationDelegate = self;
    self.qContentWebView.scrollView.bounces = NO;
    self.qContentWebView.backgroundColor = [UIColor clearColor];
    self.qContentWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.qContentWebView.scrollView.scrollEnabled = NO;
    self.qContentWebView.opaque = NO;
    [self.bgScrollView addSubview:self.qContentWebView];
    self.qContentWebView.hidden = YES;
    
    //阅读内容
    NSString *jScript = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 32];
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;
    self.contentWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16,24,self.currentAvailableWidth-32,0) configuration:wkWebConfig];
    self.contentWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.contentWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.contentWebView.UIDelegate = self;
    self.contentWebView.navigationDelegate = self;
    self.contentWebView.scrollView.bounces = NO;
    self.contentWebView.backgroundColor = [UIColor clearColor];
    self.contentWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.contentWebView.scrollView.scrollEnabled = NO;
    self.contentWebView.opaque = NO;
    [self.bgScrollView addSubview:self.contentWebView];
    self.contentWebView.hidden = YES;
    
    //合并的小题内容
    NSString *jScript3 = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 32];
    WKUserScript *wkUScript3 = [[WKUserScript alloc] initWithSource:jScript3 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController3 = [[WKUserContentController alloc] init];
    [wkUController3 addUserScript:wkUScript3];
    WKWebViewConfiguration *wkWebConfig3 = [[WKWebViewConfiguration alloc] init];
    wkWebConfig3.userContentController = wkUController3;
    self.mergeWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16,24,self.currentAvailableWidth-32,0) configuration:wkWebConfig3];
    self.mergeWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.mergeWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.mergeWebView.UIDelegate = self;
    self.mergeWebView.navigationDelegate = self;
    self.mergeWebView.scrollView.bounces = NO;
    self.mergeWebView.backgroundColor = [UIColor clearColor];
    self.mergeWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.mergeWebView.scrollView.scrollEnabled = NO;
    self.mergeWebView.opaque = NO;
    [self.bgScrollView addSubview:self.mergeWebView];
    self.mergeWebView.hidden = YES;
    
    
    self.btnScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(16,CGRectGetMaxY(self.contentWebView.frame)+36,self.currentAvailableWidth-32,32)];
    self.btnScrollView.backgroundColor = UIColorHex(0xF2F7F6);
    self.btnScrollView.showsHorizontalScrollIndicator = NO;
    [self.bgScrollView addSubview:self.btnScrollView];
    
    self.line = [[UIView alloc]initWithFrame:CGRectMake(16,CGRectGetMaxY(self.btnScrollView.frame), self.currentAvailableWidth-32,1)];
    self.line.backgroundColor = UIColorHex(0xEBF0EF);
    [self.bgScrollView addSubview:self.line];
    
    self.tvScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.btnScrollView.frame)+1,self.currentAvailableWidth,self.bgScrollView.height-16-self.total_top-37-self.btnScrollView.height)];
    self.tvScrollView.backgroundColor = UIColorHex(0xF2F7F6);
    self.tvScrollView.pagingEnabled = YES;
    self.tvScrollView.showsHorizontalScrollIndicator = NO;
    self.tvScrollView.showsVerticalScrollIndicator = NO;
    self.tvScrollView.delegate = self;
    [self.bgScrollView addSubview:self.tvScrollView];
    
    
}


-(void)createQuestionUI{
    
    if(self.model.type.integerValue == 55&&self.testType == 1){
        //考试试卷 阅读b类显示提示
        self.topView.hidden = NO;
        if(self.bgScrollView.height != (self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-38-40)){
            self.bgScrollView.frame = CGRectMake(0,40, self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-38-40);
        }
    }else{
        self.topView.hidden = YES;
        if(self.bgScrollView.height != (self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-38)){
            self.bgScrollView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-38);
        }
    }

    CGFloat top = 24;
    
    self.questionView.frame = CGRectMake(16,0,self.currentAvailableWidth-32,0);
    self.questionWebView.frame = CGRectMake(16,0, self.currentAvailableWidth - 64,0);
    self.contentWebView.frame = CGRectMake(16,0,self.currentAvailableWidth-32,0);
    self.qContentWebView.frame = CGRectMake(16,0,self.currentAvailableWidth-32,0);
    self.mergeWebView.frame = CGRectMake(16,0,self.currentAvailableWidth-32,0);
    
    BOOL isShowBig = NO;
    //是否展示大题
    if((self.model.type.integerValue == 35||self.model.type.integerValue == 56||self.model.type.integerValue == 55)&&self.model.readContent){
        //三层结构的阅读题
        if((self.model.name)&&(![self.model.name isEqualToString:@""])&&(self.model.read_list_index == 0)){
            //第一篇阅读才显示大标题
            isShowBig = YES;
        }else{
            isShowBig = NO;
        }
    }else{
        if((self.model.name&&![self.model.name isEqualToString:@""])||(self.model.bigQuestionContent&&![self.model.bigQuestionContent isEqualToString:@""])){
            if(self.model.isParallel&&[self.model.isParallel isEqualToString:@"1"]){
                //并排的小题
                if(self.model.isSideNumber == YES){
                    isShowBig = NO;
                    if(self.model.questionList.count > 0){
                        ExamQuestionModel *qmodel = self.model.questionList[0];
                        if([qmodel.lsort isEqualToString:@"1"]){
                           //并排的小题存在第一个小题 才显示
                            isShowBig = YES;
                        }
                    }
                }else{
                    isShowBig = YES;
                }
                
            }else{
                //单独的只有第一个题显示
                if([self.model.lsort isEqualToString:@"1"]||!self.model.lsort){
                    isShowBig = YES;
                }else{
                    isShowBig = NO;
                }
            }
        }else{
            isShowBig = NO;
        }
    }
    
    if(isShowBig == YES){
        if(self.model.name &&![self.model.name isEqualToString:@""]){
            self.questionView.hidden = NO;
            NSString *paddingStyle = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 14px; color: #FF781D;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
            NSString *fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle,self.model.name];
            if(![self.model.name containsString:@"<p>"]){
                fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>", paddingStyle,self.model.name];
            }
            [self.questionWebView loadHTMLString:fullHTML baseURL:nil];
            top = 14+self.questionView.height+24;
        }else{
            self.questionView.hidden = YES;
        }
        if(self.model.bigQuestionContent&&![self.model.bigQuestionContent isEqualToString:@""]){
            self.qContentWebView.hidden = NO;
            NSString *paddingStyle3 = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 16px; color: #1C1F1E; line-height: 2; letter-spacing: 2px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
            NSString *fullHTML3 = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle3,self.model.bigQuestionContent];
            if(![self.model.bigQuestionContent containsString:@"<p>"]){
                fullHTML3 = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>", paddingStyle3,self.model.bigQuestionContent];
            }
            [self.qContentWebView loadHTMLString:fullHTML3 baseURL:nil];
            top = top+self.qContentWebView.height+24;
        }else{
            self.qContentWebView.hidden = YES;
        }
    }else{
        self.questionView.hidden = YES;
        self.qContentWebView.hidden = YES;
    }
    self.contentWebView.frame = CGRectMake(16,top,self.currentAvailableWidth-32,0);
    if((self.model.type.integerValue == 35||self.model.type.integerValue == 56||self.model.type.integerValue == 55)&&(self.model.readContent)&&(![self.model.readContent isEqualToString:@""])){
        self.contentWebView.hidden = NO;
        NSString *paddingStyle2 = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 16px; color: #1C1F1E; line-height: 2; letter-spacing: 2px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
        NSString *fullHTML2 = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>",paddingStyle2, self.model.readContent];
        if(self.model.readContent&&![self.model.readContent containsString:@"<p>"]){
            fullHTML2 = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>",paddingStyle2, self.model.readContent];
        }else{
            if(!self.model.readContent){
                fullHTML2 = [NSString stringWithFormat:@"<html><head>%@</head><body><p></p></body></html>",paddingStyle2];
            }
        }
        [self.contentWebView loadHTMLString:fullHTML2 baseURL:nil];
        top = top+self.contentWebView.height+24;
    }else{
        self.contentWebView.hidden = YES;
    }
    
    self.mergeWebView.frame = CGRectMake(16,CGRectGetMaxY(self.contentWebView.frame)+24,self.currentAvailableWidth-32,0);
    if(self.model.isSideNumber == YES&&self.model.mergeContent&&![self.model.mergeContent isEqualToString:@""]){
        self.mergeWebView.hidden = NO;
        NSString *paddingStyle4 = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 17px; color: #1C1F1E;letter-spacing: 1px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
        NSString *fullHTML4 = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>",paddingStyle4, self.model.mergeContent];
        if(self.model.mergeContent&&![self.model.mergeContent containsString:@"<p>"]){
            fullHTML4 = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>",paddingStyle4, self.model.mergeContent];
        }else{
            if(!self.model.mergeContent){
                fullHTML4 = [NSString stringWithFormat:@"<html><head>%@</head><body><p></p></body></html>",paddingStyle4];
            }
        }
        [self.mergeWebView loadHTMLString:fullHTML4 baseURL:nil];
        top = top+self.mergeWebView.height+24;
    }else{
        self.mergeWebView.hidden = YES;
    }
    
    if(top > 24){
        self.btnScrollView.frame = CGRectMake(16,top+36,self.currentAvailableWidth-32,32);
    }else{
        self.btnScrollView.frame = CGRectMake(16,top,self.currentAvailableWidth-32,32);
    }
    self.line.frame = CGRectMake(16,CGRectGetMaxY(self.btnScrollView.frame),self.currentAvailableWidth-32,1);
    [self.btnScrollView removeAllSubviews];
    [self.tvScrollView removeAllSubviews];
    NSArray *questionArr = self.model.questionList;
    CGFloat max_h = 0;
    if(questionArr.count > 1){
        self.btnScrollView.hidden = NO;
        self.line.hidden = NO;
        CGFloat left = 0;
        for(NSInteger i = 0;i < questionArr.count;i++){
            ExamQuestionModel *qmodel = questionArr[i];
            NSString *sortId = [NSString stringWithFormat:@"%@",qmodel.sortId?qmodel.sortId:@""];
            if(self.model.isSideNumber == YES){
                sortId = [NSString stringWithFormat:@"%@",qmodel.name?qmodel.name:@""];
            }
            CGFloat s_w = [self getStringWidthWithText:sortId font:JPUIFontPingFangSCMedium(17) viewHeight:32];
            if(s_w < 43){
                s_w = 43;
            }
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(left,0,s_w,32)];
            [btn setTitle:sortId forState:UIControlStateNormal];
            [btn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
            [btn setTitleColor:KFontBlackColor forState:UIControlStateSelected];
            btn.titleLabel.font = JPUIFontPingFangSCMedium(17);
            btn.tag = 1000+i;
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [self.btnScrollView addSubview:btn];
            left = left+s_w+12;
            UIView *btn_line = [[UIView alloc]init];
            btn_line.backgroundColor = KThemeColor;
            btn_line.layer.cornerRadius = 1;
            btn_line.layer.masksToBounds = YES;
            btn_line.tag = 3000+i;
            [btn addSubview:btn_line];
            [btn_line mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(@20);
                make.height.mas_equalTo(@2);
                make.centerX.mas_equalTo(btn);
                make.bottom.mas_equalTo(@0);
            }];
            if(i == self.model.read_question_index){
                btn.selected = YES;
                btn_line.hidden = NO;
            }else{
                btn.selected = NO;
                btn_line.hidden = YES;
            }
            
    
            CGFloat optios_h = 0;
            if([qmodel.isSelect isEqualToString:@"1"]||qmodel.isSelect.integerValue == 1){
                for(NSInteger o = 0;o < qmodel.questionOptions.count;o++){
                    ExamQuestionOptionsModel *optionsModel = qmodel.questionOptions[o];
                    CGFloat o_h = [self getHeightWithModel:qmodel andQmodel:optionsModel];
                    optios_h = optios_h+o_h;
                }
            }
            CGFloat total_h = 30+optios_h+93;
            //如果有查看了解析
            UILabel *analysisLabel = [[UILabel alloc]initWithFrame:CGRectMake(20,56,self.currentAvailableWidth-40,0)];
            analysisLabel.numberOfLines = 0;
            analysisLabel.attributedText = [self changeAnalysisStr:qmodel.analysis?qmodel.analysis:@""];
            CGFloat a_h = 0;
            if(([qmodel.isSelect isEqualToString:@"0"]||qmodel.isSelect.integerValue == 0)&&self.testType == 0){
                total_h = total_h+72;
            }else{
                if((qmodel.isDone&&[qmodel.isDone isEqualToString:@"1"])||self.testType == 2||self.testType == 3||self.testType == 4){
                    CGSize a_size = [analysisLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
                    a_h = a_size.height;
                    analysisLabel.frame = CGRectMake(20,56,self.currentAvailableWidth-40,a_h);
                    total_h = total_h+a_h+56+20;
                }else if (qmodel.isDone&&[qmodel.isDone isEqualToString:@"0"]&&self.testType == 0){
                    total_h = total_h+72;
                }
            }
            if(total_h > max_h){
                max_h = total_h;
            }
            UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(i*self.currentAvailableWidth,0, self.currentAvailableWidth,total_h) style:UITableViewStylePlain];
            tableView.backgroundColor = UIColorHex(0xF2F7F6);
            tableView.delegate = self;
            tableView.dataSource = self;
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            [tableView registerClass:NSClassFromString(@"ExamQuestionsListCell") forCellReuseIdentifier:@"ExamQuestionsListCell"];
            tableView.showsVerticalScrollIndicator = NO;
            tableView.bounces = NO;
            tableView.tag = 2000+i;
            [self.tvScrollView addSubview:tableView];
            
            UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,30)];
            headerView.backgroundColor = UIColorHex(0xF2F7F6);
            headerView.tag = 200+i;
            tableView.tableHeaderView = headerView;
            NSString *jScript = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 32];
            WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
            WKUserContentController *wkUController = [[WKUserContentController alloc] init];
            [wkUController addUserScript:wkUScript];
            WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
            wkWebConfig.userContentController = wkUController;
            WKWebView *titleWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16,24,self.currentAvailableWidth-32,0) configuration:wkWebConfig];
            titleWebView.scrollView.showsVerticalScrollIndicator = NO;
            titleWebView.scrollView.showsHorizontalScrollIndicator = NO;
            titleWebView.UIDelegate = self;
            titleWebView.navigationDelegate = self;
            titleWebView.scrollView.bounces = NO;
            titleWebView.backgroundColor = [UIColor clearColor];
            titleWebView.scrollView.backgroundColor = [UIColor clearColor];
            titleWebView.scrollView.scrollEnabled = NO;
            titleWebView.opaque = NO;
            titleWebView.tag = 100+i;
            [headerView addSubview:titleWebView];
            NSString *paddingStyle3 = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 17px; color: #1C1F1E;letter-spacing: 1px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
            if(self.model.isSideNumber == YES){
                qmodel.content = @"";
            }
            NSString *fullHTML3 = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>",paddingStyle3,qmodel.content?qmodel.content:@""];
            if(qmodel.content&&![qmodel.content containsString:@"<p>"]){
                fullHTML3 = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>",paddingStyle3, qmodel.content];
            }else{
                if(!qmodel.content){
                    fullHTML3 = [NSString stringWithFormat:@"<html><head>%@</head><body><p></p></body></html>",paddingStyle3];
                }
            }
            [titleWebView loadHTMLString:fullHTML3 baseURL:nil];
            
            UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,93)];
            footerView.backgroundColor = UIColorHex(0xF2F7F6);
            if((qmodel.isDone&&[qmodel.isDone isEqualToString:@"1"])||self.testType == 2||self.testType == 3||self.testType == 4){
                footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,a_h+56+20+93);
                UIView *analysisView = [[UIView alloc]initWithFrame:CGRectMake(0,0,self.currentAvailableWidth,a_h+56+20)];
                analysisView.backgroundColor = UIColorHex(0xF2F7F6);
                CGFloat left_w = (self.currentAvailableWidth-94)/2.0;
                UILabel *analysisTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(left_w, 20, 94, 20)];
                analysisTitleLabel.font = JPUIFontPingFangSCRegular(15);
                analysisTitleLabel.textColor = KFontGrayColor;
                analysisTitleLabel.textAlignment = NSTextAlignmentCenter;
                analysisTitleLabel.text = @"答案解析";
                [analysisView addSubview:analysisTitleLabel];
                UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(20,29.5, left_w-20,1)];
                leftView.backgroundColor = UIColorHex(0xEBF0EF);
                [analysisView addSubview:leftView];
                UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(self.currentAvailableWidth-left_w,29.5, left_w-20,1)];
                rightView.backgroundColor = UIColorHex(0xEBF0EF);
                [analysisView addSubview:rightView];
                
                [analysisView addSubview:analysisLabel];
                [footerView addSubview:analysisView];
            }else if (((qmodel.isDone&&[qmodel.isDone isEqualToString:@"0"])||[qmodel.isSelect isEqualToString:@"0"]||qmodel.isSelect.integerValue == 0)&&self.testType == 0){
                footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,72+93);
                UIButton *checkBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.currentAvailableWidth-16-96,10,96,42)];
                [checkBtn setTitle:@"查看解析" forState:UIControlStateNormal];
                [checkBtn setTitleColor:KFontBlackColor forState:UIControlStateNormal];
                checkBtn.titleLabel.font = JPUIFontPingFangSCRegular(16);
                checkBtn.backgroundColor = [UIColor whiteColor];
                checkBtn.layer.cornerRadius = 10;
                checkBtn.layer.masksToBounds = YES;
                [checkBtn addTarget:self action:@selector(checkBtnClick) forControlEvents:UIControlEventTouchUpInside];
                [footerView addSubview:checkBtn];
            }
            
            tableView.tableFooterView = footerView;
            
        }
        CGFloat w = MAX(left-14,self.currentAvailableWidth-32);
        self.btnScrollView.contentSize = CGSizeMake(w,0);
    }else{
        self.btnScrollView.hidden = YES;
        self.line.hidden = YES;
        if(questionArr.count > 0){
            //只有一个问题的显示
            ExamQuestionModel *qmodel = questionArr[0];
            CGFloat optios_h = 0;
            if([qmodel.isSelect isEqualToString:@"1"]||qmodel.isSelect.integerValue == 1){
                for(NSInteger o = 0;o < qmodel.questionOptions.count;o++){
                    ExamQuestionOptionsModel *optionsModel = qmodel.questionOptions[o];
                    CGFloat o_h = [self getHeightWithModel:qmodel andQmodel:optionsModel];
                    optios_h = optios_h+o_h;
                }
            }
            CGFloat total_h = 30+optios_h+93;
            //如果有查看了解析
            UILabel *analysisLabel = [[UILabel alloc]initWithFrame:CGRectMake(20,56, self.currentAvailableWidth-40,0)];
            analysisLabel.numberOfLines = 0;
            analysisLabel.attributedText = [self changeAnalysisStr:qmodel.analysis?qmodel.analysis:@""];
            CGFloat a_h = 0;
            if(([qmodel.isSelect isEqualToString:@"0"]||qmodel.isSelect.integerValue == 0)&&self.testType == 0){
                total_h = total_h+72;
            }else{
                if((qmodel.isDone&&[qmodel.isDone isEqualToString:@"1"])||self.testType == 2||self.testType == 3||self.testType == 4){
                    CGSize a_size = [analysisLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
                    a_h = a_size.height;
                    analysisLabel.frame = CGRectMake(20,56,self.currentAvailableWidth-40,a_h);
                    total_h = total_h+a_h+56+20;
                }else if (qmodel.isDone&&[qmodel.isDone isEqualToString:@"0"]&&self.testType == 0){
                    total_h = total_h+72;
                }
            }
            if(total_h > max_h){
                max_h = total_h;
            }
            UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0,self.currentAvailableWidth,total_h) style:UITableViewStylePlain];
            tableView.backgroundColor = UIColorHex(0xF2F7F6);
            tableView.delegate = self;
            tableView.dataSource = self;
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            [tableView registerClass:NSClassFromString(@"ExamQuestionsListCell") forCellReuseIdentifier:@"ExamQuestionsListCell"];
            tableView.showsVerticalScrollIndicator = NO;
            tableView.bounces = NO;
            tableView.tag = 2000;
            [self.tvScrollView addSubview:tableView];
            
            UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,30)];
            headerView.backgroundColor = UIColorHex(0xF2F7F6);
            headerView.tag = 200;
            tableView.tableHeaderView = headerView;
            NSString *jScript = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 32];
            WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
            WKUserContentController *wkUController = [[WKUserContentController alloc] init];
            [wkUController addUserScript:wkUScript];
            WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
            wkWebConfig.userContentController = wkUController;
            WKWebView *titleWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16,24,self.currentAvailableWidth-32,0) configuration:wkWebConfig];
            titleWebView.scrollView.showsVerticalScrollIndicator = NO;
            titleWebView.scrollView.showsHorizontalScrollIndicator = NO;
            titleWebView.UIDelegate = self;
            titleWebView.navigationDelegate = self;
            titleWebView.scrollView.bounces = NO;
            titleWebView.backgroundColor = [UIColor clearColor];
            titleWebView.scrollView.backgroundColor = [UIColor clearColor];
            titleWebView.scrollView.scrollEnabled = NO;
            titleWebView.opaque = NO;
            titleWebView.tag = 100;
            [headerView addSubview:titleWebView];
            
            if(self.model.isSideNumber == YES){
                if(qmodel.name&&![qmodel.name isEqualToString:@""]){
                    qmodel.content = qmodel.name;
                }else{
                    qmodel.content = @"";
                }
            }
            NSString *htmlContent = qmodel.content?qmodel.content:@"<p></p>";
            // 题目序号
            NSString *titleNumber = @"";
            if(qmodel.sortId&&![qmodel.sortId isEqualToString:@""]){
                titleNumber = [NSString stringWithFormat:@"%@.",qmodel.sortId];
            }
            // 查找第一个 <p> 标签的位置
            NSRange pTagRange = [htmlContent rangeOfString:@"<p>"];
            // 根据是否找到 <p> 标签进行处理
            NSString *combinedHTMLContent;
            if (pTagRange.location != NSNotFound) {
                // 找到 <p> 标签，插入序号
                combinedHTMLContent = [htmlContent stringByReplacingCharactersInRange:NSMakeRange(pTagRange.location + pTagRange.length, 0) withString:titleNumber];
            } else {
                // 未找到 <p> 标签，直接在字符串前面拼接序号
                combinedHTMLContent = [NSString stringWithFormat:@"<p>%@%@</p>", titleNumber, htmlContent];
            }
            // 设置样式
            NSString *paddingStyle3 = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 17px; color: #1C1F1E;letter-spacing: 1px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
            NSString *fullHTML3 = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle3, combinedHTMLContent];
            [titleWebView loadHTMLString:fullHTML3 baseURL:nil];
            
            UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,93)];
            footerView.backgroundColor = UIColorHex(0xF2F7F6);
            if((qmodel.isDone&&[qmodel.isDone isEqualToString:@"1"])||self.testType == 2|self.testType == 3||self.testType == 4){
                footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,a_h+56+20+93);
                UIView *analysisView = [[UIView alloc]initWithFrame:CGRectMake(0,0,self.currentAvailableWidth,a_h+56+20)];
                analysisView.backgroundColor = UIColorHex(0xF2F7F6);
                CGFloat left_w = (self.currentAvailableWidth-94)/2.0;
                UILabel *analysisTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(left_w, 20, 94, 20)];
                analysisTitleLabel.font = JPUIFontPingFangSCRegular(15);
                analysisTitleLabel.textColor = KFontGrayColor;
                analysisTitleLabel.textAlignment = NSTextAlignmentCenter;
                analysisTitleLabel.text = @"答案解析";
                [analysisView addSubview:analysisTitleLabel];
                UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(20,29.5, left_w-20,1)];
                leftView.backgroundColor = UIColorHex(0xEBF0EF);
                [analysisView addSubview:leftView];
                UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(self.currentAvailableWidth-left_w,29.5, left_w-20,1)];
                rightView.backgroundColor = UIColorHex(0xEBF0EF);
                [analysisView addSubview:rightView];
                [analysisView addSubview:analysisLabel];
                [footerView addSubview:analysisView];
            }else if (((qmodel.isDone&&[qmodel.isDone isEqualToString:@"0"])||[qmodel.isSelect isEqualToString:@"0"]||qmodel.isSelect.integerValue == 0)&&self.testType == 0){
                footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,72+93);
                UIButton *checkBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.currentAvailableWidth-16-96,10,96,42)];
                [checkBtn setTitle:@"查看解析" forState:UIControlStateNormal];
                [checkBtn setTitleColor:KFontBlackColor forState:UIControlStateNormal];
                checkBtn.titleLabel.font = JPUIFontPingFangSCRegular(16);
                checkBtn.backgroundColor = [UIColor whiteColor];
                checkBtn.layer.cornerRadius = 10;
                checkBtn.layer.masksToBounds = YES;
                [checkBtn addTarget:self action:@selector(checkBtnClick) forControlEvents:UIControlEventTouchUpInside];
                [footerView addSubview:checkBtn];
            }
            
            tableView.tableFooterView = footerView;
        }
    }
    //底部tv的高
    self.max_h = max_h;
    
    CGFloat btn_h = 36;
    if(questionArr.count > 1){
        btn_h = 36+33;
    }
    
    self.total_top = top;
    CGFloat  max_total_h = self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-44;
    //如果比一个屏幕高度还小 就显示一个屏幕的
    if(max_h < (max_total_h - top-btn_h)){
        max_h = max_total_h - top-btn_h;
    }
    
    self.bgScrollView.contentSize = CGSizeMake(self.currentAvailableWidth,top+btn_h+max_h);
    if(questionArr.count > 1){
        self.tvScrollView.frame = CGRectMake(0,CGRectGetMaxY(self.btnScrollView.frame)+1,self.currentAvailableWidth,max_h);
    }else{
        if(top > 24){
            self.tvScrollView.frame = CGRectMake(0,top+36,self.currentAvailableWidth,max_h);
        }else{
            self.tvScrollView.frame = CGRectMake(0,top,self.currentAvailableWidth,max_h);
        }
    }
    
    [self.tvScrollView setContentOffset:CGPointMake(self.model.read_question_index*self.currentAvailableWidth,0) animated:NO];
    
    self.tvScrollView.contentSize = CGSizeMake(self.model.questionList.count*self.currentAvailableWidth,0);
    
}

#pragma mark - 富文本转化成只带划线的文本
- (NSAttributedString *)parseHTMLString:(NSString *)htmlString withFont:(UIFont *)font color:(UIColor *)color {
    // 1. 处理转义字符
    NSString *unescapedHTMLString = [self unescapeHTMLString:htmlString];
    // 2. 创建 NSMutableAttributedString
    NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] init];
    // 3. 正则表达式，匹配带有下划线的部分
    NSString *pattern = @"<span style=\"text-decoration: underline;\">(.*?)</span>";
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    if (error) {
        NSLog(@"正则表达式错误: %@", error.localizedDescription);
        return [[NSAttributedString alloc] initWithString:htmlString attributes:@{NSFontAttributeName: font, NSForegroundColorAttributeName: color}];
    }
    __block NSUInteger lastLocation = 0;
    
    // 4. 设置段落样式为按字符换行
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;  // 设置按字符换行
    
    NSDictionary *normalAttributes = @{NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: paragraphStyle};
    NSDictionary *underlineAttributes = @{NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle), NSParagraphStyleAttributeName: paragraphStyle};
    
    // 5. 处理匹配的文本
    [regex enumerateMatchesInString:unescapedHTMLString options:0 range:NSMakeRange(0, unescapedHTMLString.length) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
        // 处理普通文本部分
        if (match.range.location > lastLocation) {
            NSString *normalText = [unescapedHTMLString substringWithRange:NSMakeRange(lastLocation, match.range.location - lastLocation)];
            normalText = [self stripHTMLTags:normalText];
            NSMutableAttributedString *normalAttributedString = [[NSMutableAttributedString alloc] initWithString:normalText attributes:normalAttributes];
            [resultString appendAttributedString:normalAttributedString];
        }
        
        // 处理下划线文本部分
        NSRange underlineRange = [match rangeAtIndex:1];
        NSString *underlineText = [unescapedHTMLString substringWithRange:underlineRange];
        NSMutableAttributedString *underlinedAttributedString = [[NSMutableAttributedString alloc] initWithString:underlineText attributes:underlineAttributes];
        [resultString appendAttributedString:underlinedAttributedString];
        
        lastLocation = match.range.location + match.range.length;
    }];
    
    // 处理剩余的普通文本部分
    if (lastLocation < unescapedHTMLString.length) {
        NSString *remainingText = [unescapedHTMLString substringFromIndex:lastLocation];
        remainingText = [self stripHTMLTags:remainingText];
        NSMutableAttributedString *remainingAttributedString = [[NSMutableAttributedString alloc] initWithString:remainingText attributes:normalAttributes];
        [resultString appendAttributedString:remainingAttributedString];
    }
    
    return resultString;
}

// 移除 HTML 标签的辅助方法
-(NSString *)stripHTMLTags:(NSString *)htmlString {
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<[^>]+>" options:0 error:nil];
    NSString *cleanedString = [regex stringByReplacingMatchesInString:htmlString options:0 range:NSMakeRange(0, htmlString.length) withTemplate:@""];
    return cleanedString;
}

// 恢复 HTML 转义字符的辅助方法
- (NSString *)unescapeHTMLString:(NSString *)htmlString {
    NSString *unescapedString = [htmlString stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];
    return unescapedString;
}



#pragma mark - 解析选择刷新
-(void)refreshCheck{
    if(self.model.read_question_index < self.model.questionList.count){
        CGFloat max_h = self.tvScrollView.size.height;
        ExamQuestionModel *qmodel = self.model.questionList[self.model.read_question_index];
        UITableView *tableView = [self.tvScrollView viewWithTag:2000+self.model.read_question_index];
        UIView *headerView = [self.tvScrollView viewWithTag:200+self.model.read_question_index];
        CGFloat optios_h = 0;
        if([qmodel.isSelect isEqualToString:@"1"]||qmodel.isSelect.integerValue == 1){
            for(NSInteger o = 0;o < qmodel.questionOptions.count;o++){
                ExamQuestionOptionsModel *optionsModel = qmodel.questionOptions[o];
                CGFloat o_h = [self getHeightWithModel:qmodel andQmodel:optionsModel];
                optios_h = optios_h+o_h;
            }
        }
        CGFloat total_h = headerView.height+optios_h+93;
        //如果有查看了解析
        UILabel *analysisLabel = [[UILabel alloc]initWithFrame:CGRectMake(20,56,self.currentAvailableWidth-40,0)];
        analysisLabel.numberOfLines = 0;
        analysisLabel.attributedText = [self changeAnalysisStr:qmodel.analysis?qmodel.analysis:@""];
        CGFloat a_h = 0;
        if((qmodel.isDone&&[qmodel.isDone isEqualToString:@"1"])||self.testType == 2||self.testType == 3||self.testType == 4){
            CGSize a_size = [analysisLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
            a_h = a_size.height;
            analysisLabel.frame = CGRectMake(20,56,self.currentAvailableWidth-40,a_h);
            total_h = total_h+a_h+56+20;
        }else if (qmodel.isDone&&[qmodel.isDone isEqualToString:@"0"]&&self.testType == 0){
            total_h = total_h+72;
        }
        if(total_h > max_h){
            max_h = total_h;
        }
        tableView.frame = CGRectMake(self.model.read_question_index*self.currentAvailableWidth,0,self.currentAvailableWidth,total_h);
        UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,93)];
        footerView.backgroundColor = UIColorHex(0xF2F7F6);
        if((qmodel.isDone&&[qmodel.isDone isEqualToString:@"1"])||self.testType == 2||self.testType == 3||self.testType == 4){
            footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,a_h+56+20+93);
            UIView *analysisView = [[UIView alloc]initWithFrame:CGRectMake(0,0,self.currentAvailableWidth,a_h+56+20)];
            analysisView.backgroundColor = UIColorHex(0xF2F7F6);
            CGFloat left_w = (self.currentAvailableWidth-94)/2.0;
            UILabel *analysisTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(left_w, 20, 94, 20)];
            analysisTitleLabel.font = JPUIFontPingFangSCRegular(15);
            analysisTitleLabel.textColor = KFontGrayColor;
            analysisTitleLabel.textAlignment = NSTextAlignmentCenter;
            analysisTitleLabel.text = @"答案解析";
            [analysisView addSubview:analysisTitleLabel];
            UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(20,29.5, left_w-20,1)];
            leftView.backgroundColor = UIColorHex(0xEBF0EF);
            [analysisView addSubview:leftView];
            UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(self.currentAvailableWidth-left_w,29.5, left_w-20,1)];
            rightView.backgroundColor = UIColorHex(0xEBF0EF);
            [analysisView addSubview:rightView];
            [analysisView addSubview:analysisLabel];
            [footerView addSubview:analysisView];
        }else if (qmodel.isDone&&[qmodel.isDone isEqualToString:@"0"]&&self.testType == 0){
            footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,72+93);
             UIButton *checkBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.currentAvailableWidth-16-96,10,96,42)];
             [checkBtn setTitle:@"查看解析" forState:UIControlStateNormal];
             [checkBtn setTitleColor:KFontBlackColor forState:UIControlStateNormal];
             checkBtn.titleLabel.font = JPUIFontPingFangSCRegular(16);
             checkBtn.backgroundColor = [UIColor whiteColor];
             checkBtn.layer.cornerRadius = 10;
             checkBtn.layer.masksToBounds = YES;
             [checkBtn addTarget:self action:@selector(checkBtnClick) forControlEvents:UIControlEventTouchUpInside];
             [footerView addSubview:checkBtn];
        }
        
        tableView.tableFooterView = footerView;
        [tableView reloadData];
        
        CGFloat btn_h = 36;
        if(self.model.questionList.count > 1){
            btn_h = 36+33;
        }
        
        self.bgScrollView.contentSize = CGSizeMake(self.currentAvailableWidth,self.total_top+btn_h+max_h);
        if(self.model.questionList.count >1){
            self.tvScrollView.frame = CGRectMake(0,CGRectGetMaxY(self.btnScrollView.frame)+1,self.currentAvailableWidth,max_h);
        }else{
            self.tvScrollView.frame = CGRectMake(0,self.total_top+36,self.currentAvailableWidth,max_h);
        }
        self.tvScrollView.contentSize = CGSizeMake(self.model.questionList.count*self.currentAvailableWidth,0);
        
    }
   
}


#pragma mark - 考试时自动滑动
-(void)scrollToNext:(NSInteger)index{
    if(index > self.model.questionList.count-1){
        index = self.model.questionList.count-1;
        [self.tvScrollView setContentOffset:CGPointMake(index*self.currentAvailableWidth,0) animated:YES];
    }else{
        [self.tvScrollView setContentOffset:CGPointMake(index*self.currentAvailableWidth,0) animated:YES];
    }
}


#pragma mark - 题目筛选点击
-(void)btnClick:(UIButton*)button{
    
    NSInteger index = button.tag-1000;
    [self.tvScrollView setContentOffset:CGPointMake(index*self.currentAvailableWidth,0) animated:YES];
    
}

#pragma mark - scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isEqual:self.tvScrollView]) {
        NSInteger index = scrollView.contentOffset.x / self.currentAvailableWidth;
        UIButton *oldBtn = [self.btnScrollView viewWithTag:1000 + self.model.read_question_index];
        UIView *oldLine = [self.btnScrollView viewWithTag:3000 + self.model.read_question_index];
        oldBtn.selected = NO;
        oldLine.hidden = YES;

        UIButton *btn = [self.btnScrollView viewWithTag:1000 + index];
        UIView *line = [self.btnScrollView viewWithTag:3000 + index];
        btn.selected = YES;
        line.hidden = NO;

        if (self.btnScrollView.contentSize.width > (self.currentAvailableWidth - 32)) {
            if ((btn.origin.x + 43) > (self.currentAvailableWidth - 32)) {
                CGFloat x = btn.origin.x + 43 - (self.currentAvailableWidth - 32);
                if (btn.origin.x + 43 > self.btnScrollView.contentSize.width) {
                    // 最后一个
                    x = self.btnScrollView.contentSize.width - (self.currentAvailableWidth - 32);
                }
                [self.btnScrollView setContentOffset:CGPointMake(x, 0) animated:YES];
            } else {
                [self.btnScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            }
        }

        self.model.read_question_index = (index > self.model.questionList.count - 1) ? (self.model.questionList.count - 1) : index;

        // 变量isNext用于判断滑动方向状态: 0表示正常, 1表示右滑超过最后一页, 2表示左滑超过第一页
        NSInteger isNext = 0;

        // 判断是否是用户手动拖拽
        if (scrollView.isDragging) {
            // 判断是否滑动到最后一个页面并且继续右滑
            CGFloat maxOffsetX = scrollView.contentSize.width - scrollView.bounds.size.width;
            if (scrollView.contentOffset.x >= maxOffsetX) {
                // 滑动到最后一页
                if (scrollView.contentOffset.x > maxOffsetX) {
                    // 继续右滑超过最后一页
                    isNext = 1;
                }
            }

            // 判断是否滑动到第一个页面并且继续左滑
            if (scrollView.contentOffset.x <= 0) {
                if (scrollView.contentOffset.x < 0) {
                    // 继续左滑超过第一页
                    isNext = 2;
                }
            }
        }

        if (self.delegate && [self.delegate respondsToSelector:@selector(readQuestionScroll:andQuestionModel:andIsNext:)]) {
            if (self.model.read_question_index < self.model.questionList.count) {
                [self.delegate readQuestionScroll:self andQuestionModel:self.model.questionList[self.model.read_question_index] andIsNext:isNext];
            }
        }
    }
}



#pragma mark - tableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ExamQuestionsListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExamQuestionsListCell"];
    cell.row = indexPath.row;
    NSInteger tag_index = tableView.tag-2000;
    if(tag_index < self.model.questionList.count){
        ExamQuestionModel *model = self.model.questionList[tag_index];
        if(indexPath.row < model.questionOptions.count){
            ExamQuestionOptionsModel *qmodel = model.questionOptions[indexPath.row];
            cell.model = qmodel;
            if((model.doAnswer&&![model.doAnswer isEqualToString:@""]&&model.isDone&&[model.isDone isEqualToString:@"1"])||(self.testType == 2)||(self.testType == 3)||(self.testType == 4)){
                //有答题 直接显示答案和对错
                if([model.correct isEqualToString:@"1"]){
                    //正确
                    if([model.answer isEqualToString:qmodel.optionKey]){
                        cell.type = 2;
                    }else{
                        cell.type = 0;
                    }
                }else{
                    //错误
                    if([model.doAnswer isEqualToString:qmodel.optionKey]){
                        cell.type = 3;
                    }else if ([model.answer isEqualToString:qmodel.optionKey]){
                        cell.type = 2;
                    }else{
                        cell.type = 0;
                    }
                }
            }else{
                //没有答题
                if(model.isDone&&[model.isDone isEqualToString:@"0"]){
                    //做题的时候选择过
                    if([model.doAnswer isEqualToString:qmodel.optionKey]){
                        cell.type = 1;
                    }else{
                        cell.type = 0;
                    }
                }else{
                    cell.type = 0;
                }
            }
        }
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger tag_index = tableView.tag-2000;
    if(tag_index < self.model.questionList.count){
        ExamQuestionModel *model = self.model.questionList[tag_index];
        if([model.isSelect isEqualToString:@"1"]||model.isSelect.integerValue == 1){
            return model.questionOptions.count;
        }
        return 0;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.testType == 0||self.testType == 1){
        ExamQuestionsListCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSInteger tag_index = tableView.tag-2000;
        if(tag_index < self.model.questionList.count){
            ExamQuestionModel *model = self.model.questionList[tag_index];
            if (!(model.isDone&&[model.isDone isEqualToString:@"1"])){
                //没有答案就能点击
                ExamQuestionOptionsModel *qmodel = model.questionOptions[indexPath.row];
                [cell animateBgViewWithCompletion:^{
                    if (self.delegate && [self.delegate respondsToSelector:@selector(answerReadQuestionTap:andQuestionModel:andOptionsModel:)]){
                        [self.delegate answerReadQuestionTap:self andQuestionModel:model andOptionsModel:qmodel];
                    }
                }];
            }
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger tag_index = tableView.tag-2000;
    if(tag_index < self.model.questionList.count){
        ExamQuestionModel *model = self.model.questionList[tag_index];
        if(indexPath.row < model.questionOptions.count){
            ExamQuestionOptionsModel *qmodel = model.questionOptions[indexPath.row];
            CGFloat h = [self getHeightWithModel:model andQmodel:qmodel];
            return h;
        }
    }
    
    return 74;
}

#pragma mark - 取出图片宽高
- (NSArray *)extractImageSizeFromHTMLString:(NSString *)htmlString {
    NSMutableArray *resultArray = [NSMutableArray arrayWithObjects:@"0", @"0", nil];
    
    NSString *pattern = @"<img[^>]+width\\s*=\\s*\"(\\d+)\"[^>]*height\\s*=\\s*\"(\\d+)\"";
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    
    if (error) {
        NSLog(@"正则表达式错误: %@", error.localizedDescription);
        return resultArray;
    }
    
    NSTextCheckingResult *match = [regex firstMatchInString:htmlString options:0 range:NSMakeRange(0, [htmlString length])];
    if (match) {
        if ([match rangeAtIndex:1].location != NSNotFound) {
            NSString *width = [htmlString substringWithRange:[match rangeAtIndex:1]];
            resultArray[0] = width ? width : @"0";
        }
        
        if ([match rangeAtIndex:2].location != NSNotFound) {
            NSString *height = [htmlString substringWithRange:[match rangeAtIndex:2]];
            resultArray[1] = height ? height : @"0";
        }
    }
    
    return resultArray;
}


#pragma mark - 查看解析
-(void)checkBtnClick{
    
    if(self.testType == 0){
        if(self.model.read_question_index < self.model.questionList.count){
            ExamQuestionModel *model = self.model.questionList[self.model.read_question_index];
            if (self.delegate && [self.delegate respondsToSelector:@selector(checkReadQuestionTap:andQuestionModel:)]){
                [self.delegate checkReadQuestionTap:self andQuestionModel:model];
            }
        }
    }
    
}

#pragma mark - 获取选项高度
-(CGFloat)getHeightWithModel:(ExamQuestionModel*)model andQmodel:(ExamQuestionOptionsModel*)qmodel{
    NSInteger type = 0;
    if((model.doAnswer&&![model.doAnswer isEqualToString:@""]&&model.isDone&&[model.isDone isEqualToString:@"1"])||(self.testType == 2)||(self.testType == 3)||(self.testType == 4)){
        //有答题 直接显示答案和对错
        if([model.correct isEqualToString:@"1"]){
            //正确
            if([model.answer isEqualToString:qmodel.optionKey]){
                type = 2;
            }else{
                type = 0;
            }
        }else{
            //错误
            if([model.doAnswer isEqualToString:qmodel.optionKey]){
                type = 3;
            }else if ([model.answer isEqualToString:qmodel.optionKey]){
                type = 2;
            }else{
                type = 0;
            }
        }
    }else{
        //没有答题
        if(model.isDone&&[model.isDone isEqualToString:@"0"]){
            //做题的时候选择过
            if([model.doAnswer isEqualToString:qmodel.optionKey]){
                type = 1;
            }else{
                type = 0;
            }
        }else{
            type = 0;
        }
    }
    
    CGFloat max_w = self.currentAvailableWidth-32-16-47;
    if(type == 3){
        //显示错误时
        max_w = self.currentAvailableWidth-32-32-47-20;
    }
    if(qmodel.optionValue&&[qmodel.optionValue containsString:@"<img src="]){
        //图片
        NSArray *arr = [self extractImageSizeFromHTMLString:qmodel.optionValue];
        if(arr.count == 2){
            NSString *pic_w = arr[0];
            NSString *pic_h = arr[1];
            CGFloat w = pic_w.floatValue;
            CGFloat h = pic_h.floatValue;
            if(w > max_w){
                w = max_w;
                h = w*pic_h.floatValue/pic_w.floatValue;
            }
            return h+52;
        }
    }else{
        if(!self.optionTitleLabel){
            self.optionTitleLabel = [[UILabel alloc]init];
            self.optionTitleLabel.numberOfLines = 0;
            self.optionTitleLabel.textColor = KFontBlackColor;
            self.optionTitleLabel.font = JPUIFontPingFangSCRegular(16);
        }
        self.optionTitleLabel.attributedText = [self parseHTMLString:qmodel.optionValue?qmodel.optionValue:@"" withFont:self.optionTitleLabel.font color:self.optionTitleLabel.textColor];
        CGSize size = [self.optionTitleLabel sizeThatFits:CGSizeMake(max_w,MAXFLOAT)];
        if(size.height < 22){
            size.height = 22;
        }
        return size.height+52;
    }
    return 74;
}

#pragma mark - webview delegate 高度
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // 执行 JavaScript 以获取页面内容的高度
    [webView evaluateJavaScript:@"document.documentElement.scrollHeight" completionHandler:^(id result, NSError *error) {
        if (!error) {
            CGFloat height = [result doubleValue];
            CGFloat h = height-16;
            if(h < 0){
                h = 0;
            }
            if ([webView isEqual:self.questionWebView]){
                webView.frame = CGRectMake(16,10, self.currentAvailableWidth - 64,h);
                if(h == 0){
                    self.questionView.frame = CGRectMake(16,14,self.currentAvailableWidth-32,0);
                    self.questionView.hidden = YES;
                }else{
                    self.questionView.hidden = NO;
                    self.questionView.frame = CGRectMake(16,14,self.currentAvailableWidth-32,h+20);
                }
                
            }else if ([webView isEqual:self.contentWebView]){
                webView.frame = CGRectMake(16,24,self.currentAvailableWidth-32,h);
            }else if ([webView isEqual:self.qContentWebView]){
                webView.frame = CGRectMake(16,24,self.currentAvailableWidth-32,h);
            }else if ([webView isEqual:self.mergeWebView]){
                webView.frame = CGRectMake(16,24,self.currentAvailableWidth-32,h);
            }else{
                webView.frame = CGRectMake(16,24,self.currentAvailableWidth-32,h);
                NSInteger index = webView.tag-100;
                UITableView *tableView = [self.tvScrollView viewWithTag:2000+index];
                tableView.frame = CGRectMake(index*self.currentAvailableWidth,0,self.currentAvailableWidth,tableView.height+h);
                UIView *headerView = [self.tvScrollView viewWithTag:200+index];
                headerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,30+h);
                tableView.tableHeaderView = headerView;
                if(tableView.height > self.max_h){
                    self.max_h = tableView.height;
                }
            }
            
            CGFloat top_h = [self getTotalTopHeight];
            self.total_top = top_h;
            if(top_h > 24){
                self.btnScrollView.frame = CGRectMake(16,top_h+36,self.currentAvailableWidth-32,32);
            }else{
                self.btnScrollView.frame = CGRectMake(16,top_h,self.currentAvailableWidth-32,32);
            }
            self.line.frame = CGRectMake(16,CGRectGetMaxY(self.btnScrollView.frame),self.currentAvailableWidth-32,1);
            
            CGFloat btn_h = 36;
            if(self.model.questionList.count > 1){
                btn_h = 36+33;
            }
            CGFloat  max_total_h = self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-44;
            //如果比一个屏幕高度还小 就显示一个屏幕的
            if(self.max_h < (max_total_h - top_h-btn_h)){
                self.max_h = max_total_h - top_h-btn_h;
            }
            self.bgScrollView.contentSize = CGSizeMake(self.currentAvailableWidth,top_h+btn_h+self.max_h);
            if(self.model.questionList.count > 1){
                self.tvScrollView.frame = CGRectMake(0,CGRectGetMaxY(self.btnScrollView.frame)+1,self.currentAvailableWidth,self.max_h);
            }else{
                if(top_h > 24){
                    self.tvScrollView.frame = CGRectMake(0,top_h+36,self.currentAvailableWidth,self.max_h);
                }else{
                    self.tvScrollView.frame = CGRectMake(0,top_h,self.currentAvailableWidth,self.max_h);
                }
            }
            self.tvScrollView.contentSize = CGSizeMake(self.model.questionList.count*self.currentAvailableWidth,0);
        }
    }];
}

#pragma mark - 获取头部高度
-(CGFloat)getTotalTopHeight{
    
    CGFloat top_h = 0;
    //大题题目
    if(self.questionWebView.height > 0){
        self.questionView.hidden = NO;
        top_h = 14+self.questionView.height+24;
    }else{
        top_h = 24;
        self.questionView.hidden = YES;
    }
    
    //大题内容
    if(self.qContentWebView.height > 0){
        self.qContentWebView.hidden = NO;
        self.qContentWebView.top = top_h;
        top_h = top_h+self.qContentWebView.height+24;
    }else{
        self.qContentWebView.hidden = YES;
    }
    
    
    //阅读内容
    if(self.contentWebView.height > 0){
        self.contentWebView.hidden = NO;
        self.contentWebView.top = top_h;
        top_h = top_h+self.contentWebView.height+24;
    }else{
        self.contentWebView.hidden = YES;
    }
    
    //合并内容
    if(self.mergeWebView.height > 0){
        self.mergeWebView.hidden = NO;
        self.mergeWebView.top = top_h;
        top_h = top_h+self.mergeWebView.height+24;
    }else{
        self.mergeWebView.hidden = YES;
    }
    
    return top_h;
    
}


-(NSMutableAttributedString*)changeAnalysisStr:(NSString*)str{
    
    NSMutableAttributedString *pStr = [[NSMutableAttributedString alloc]initWithString:str];
    // 创建一个 NSMutableParagraphStyle 实例来设置行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 10;  // 设置您想要的行间距
    // 将字体和颜色属性应用到整个字符串
    [pStr addAttribute:NSFontAttributeName value:JPUIFontPingFangSCRegular(15) range:NSMakeRange(0, pStr.length)];
    [pStr addAttribute:NSForegroundColorAttributeName value:KFontGrayColor range:NSMakeRange(0, pStr.length)];
    // 将段落样式应用到整个字符串
    [pStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, pStr.length)];
    
    return pStr;
    
}


@end
